package com.example.shutdown_v1.controller;

import com.example.shutdown_v1.repository.SensorDataRepository;
import com.example.shutdown_v1.repository.SwitchStateRecordRepository;
import com.example.shutdown_v1.schedule.DataCleanupScheduler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据清理管理API
 * 提供手动清理和查询功能
 */
@Slf4j
@RestController
@RequestMapping("/api/cleanup")
@RequiredArgsConstructor
public class DataCleanupController {

    private final DataCleanupScheduler cleanupScheduler;
    private final SensorDataRepository sensorDataRepository;
    private final SwitchStateRecordRepository stateRecordRepository;

    /**
     * 手动触发数据清理
     * POST /api/cleanup/execute
     */
    @PostMapping("/execute")
    public ResponseEntity<Map<String, Object>> executeCleanup() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            log.info("[手动清理] API触发数据清理");
            cleanupScheduler.manualCleanup();
            
            response.put("success", true);
            response.put("message", "数据清理执行完成");
            response.put("timestamp", LocalDateTime.now());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("[手动清理] 执行失败", e);
            response.put("success", false);
            response.put("message", "清理失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 查询数据统计信息
     * GET /api/cleanup/stats
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getDataStats(
            @RequestParam(defaultValue = "7") int days) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            LocalDateTime cutoffTime = LocalDateTime.now().minusDays(days);
            
            // 统计传感器数据
            long totalSensorData = sensorDataRepository.count();
            long oldSensorData = sensorDataRepository.countByReceiveTimeBefore(cutoffTime);
            
            // 统计状态记录
            long totalStateRecords = stateRecordRepository.count();
            long oldStateRecords = stateRecordRepository.countByRecordTimeBefore(cutoffTime);
            
            Map<String, Object> sensorDataStats = new HashMap<>();
            sensorDataStats.put("total", totalSensorData);
            sensorDataStats.put("olderThan" + days + "Days", oldSensorData);
            sensorDataStats.put("current", totalSensorData - oldSensorData);
            sensorDataStats.put("cutoffTime", cutoffTime);
            
            Map<String, Object> stateRecordStats = new HashMap<>();
            stateRecordStats.put("total", totalStateRecords);
            stateRecordStats.put("olderThan" + days + "Days", oldStateRecords);
            stateRecordStats.put("current", totalStateRecords - oldStateRecords);
            
            response.put("success", true);
            response.put("sensorData", sensorDataStats);
            response.put("stateRecords", stateRecordStats);
            response.put("checkDays", days);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("[数据统计] 查询失败", e);
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 清理指定天数之前的数据（危险操作，谨慎使用）
     * DELETE /api/cleanup/before-days?days=7
     */
    @DeleteMapping("/before-days")
    public ResponseEntity<Map<String, Object>> cleanupBeforeDays(
            @RequestParam int days,
            @RequestParam(defaultValue = "false") boolean confirm) {
        
        Map<String, Object> response = new HashMap<>();
        
        if (days < 1) {
            response.put("success", false);
            response.put("message", "天数必须大于0");
            return ResponseEntity.badRequest().body(response);
        }
        
        if (!confirm) {
            LocalDateTime cutoffTime = LocalDateTime.now().minusDays(days);
            long countToDelete = sensorDataRepository.countByReceiveTimeBefore(cutoffTime);
            
            response.put("success", false);
            response.put("message", "请确认删除操作");
            response.put("willDelete", countToDelete);
            response.put("cutoffTime", cutoffTime);
            response.put("hint", "添加参数 confirm=true 以确认删除");
            return ResponseEntity.ok(response);
        }
        
        try {
            LocalDateTime cutoffTime = LocalDateTime.now().minusDays(days);
            int deletedCount = sensorDataRepository.deleteByReceiveTimeBefore(cutoffTime);
            
            response.put("success", true);
            response.put("message", "清理完成");
            response.put("deletedCount", deletedCount);
            response.put("cutoffTime", cutoffTime);
            
            log.warn("[手动清理] 删除了{}天前的数据，共{}条", days, deletedCount);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("[手动清理] 删除失败", e);
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}

